/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.item

import org.ibiblio.terasaur.bt.Torrent
import org.ibiblio.terasaur.user.User
import org.grails.plugins.lookups.Lookup
import org.ibiblio.terasaur.item.Collection
import org.joda.time.DateTime
import org.joda.time.contrib.hibernate.PersistentDateTime

class Item {
    Long id
    Integer type
    String title
    String identifier
    String description
    String language
    Integer license
    DateTime published
    User owner
    Boolean deleted = false
    Collection collection
    // autoTimestamp attributes
    DateTime dateCreated
    DateTime lastUpdated

    static constraints = {
        type(nullable:false, validator: {val, obj ->
            return (Lookup.valueFor('item.type', val) != null)
        })
        title(nullable: false, blank: false)
        description(markup: true)
        language(blank:false, size: 3..3, validator: {val, obj ->
            if (Lookup.valueFor('language', val) == null) {
                return ['validator.invalid']
            } else {
                return true
            }
        })
        license(nullable:false, validator: {val, obj ->
            return (Lookup.valueFor('item.license', val) != null)
        })
        published(nullable: false)
        deleted(nullable: false)
        torrents(nullable: true)
        owner(nullable: false)
        collection(nullable: false)
        identifier(nullable: true)
    }

    static hasMany = [torrents: Torrent]
    static hasOne = [owner: User, collection: Collection]

    static mapping = {
        table 'ts_item'
        id type: 'long', generator: 'native'
        description type: 'text'
        torrents joinTable: false
        cache true
        published type: PersistentDateTime
        dateCreated type: PersistentDateTime
        lastUpdated type: PersistentDateTime
    }
}
